<template>
  <div>
    <a-upload
      :file-list="state.fileList" 
      accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      :multiple="true"
      :before-upload="beforeUpload"
      @remove="handleRemove">
      <a-button>
        <upload-outlined />
        选择附件
      </a-button>
    </a-upload>
    <a-button
      type="primary"
      :disabled="state.fileList.length === 0"
      :loading="state.uploading"
      @click="handleUpload"
    >
      {{ state.uploading ? '上传中Uploading...' : '【开始上传 Start Upload】' }}
    </a-button>
    <a-progress v-if="state.visible" :percent="state.percent" size="small" />
  </div>
</template>
<script setup>
import { reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import axios from '@/core/utils/AxiosUpload'

const props = defineProps({
  modelValue: {type: Array, default: null},
  value: {type: String, default: null},
  maxSize: {type: Number, default: null},  // 文件大小（单位: M)
  maxCount: {type: Number, default: 1},  // 文件数量
})
const emits = defineEmits(['update:modelValue', 'update:value' ])
const state = reactive({
  visible: false, 
  percent: 10,  //进度条值
  uploading: false,
  fileList: [],
  value: computed({
    get(){ return props.value},
    set(v){ 
      //  emits('update:modelValue', v)
      emits('update:value', v)
    }
  })
})

// 上传限制图片类型、大小、以及宽高尺寸
const beforeUpload= (file, fileList)=>{
  console.info('所选文件大小：', file.size, ', 文件名：', file.name)
  if(props.maxSize && (file.size /(1024*1024) > props.maxSize)){
    fileList.splice(fileList.indexOf(file),1)
    message.error(file.name, ', 文件不能大于'+props.maxSize+ 'm.', 3)
    return false
  }
  state.fileList = fileList
  return false
}

// 册除文件
const handleRemove = (file)=>{
  // TODO 后台删除文件
  const index = state.fileList.indexOf(file)
  const newFileList = state.fileList.slice()
  newFileList.splice(index, 1)
  state.fileList = newFileList
  message.error('移去成功。。')
}

// 上传文件
const handleUpload = () => {
  state.uploading = true
  const formData = new FormData()
  state.fileList.forEach(file => {
    // console.log(file)
    formData.append('files', file)
  })
  // 提交换后台处理
  // const source = axios.CancelToken.source()
  //   // 取消请求
  // source.cancel('取消上传')
  axios.post('/api/Upload/doUploadAttach', formData, {
    onUploadProgress: progressEvent => {
      const progress = Math.round(progressEvent.loaded / progressEvent.total * 100)
      console.log('上传进度：' + progress + '%')
    }
  }).then( res => {
    if(res.code == 0) {
      state.fileList.forEach(file=>{
        file.status = 'done'
      })
      message.success('上传成功【upload successfully.】')
    }else {
      message.error('上传失败::'+ res.msg)
    }
  }).catch(() => {
    message.error('上传失败[upload failed.]')
  }).finally(()=>{
    state.uploading = false
  })
}
</script>